#!/bin/sh

if [ "$1" == "--help" ] || [ "$1" == "-h" ] ; then
	echo
	echo " ------------------------------------------------------------------------------"
	echo "  format: sh $0 <php53s/php54s>"
	echo " ------------------------------------------------------------------------------"
	echo
	exit
fi

INIT_DIR="/usr/local/lxlabs/kloxo/init"

if [ "$1" != "" ] ; then
	 if [[ "$1" != "php"* ]] ; then
		echo "Use 'sh $0 --help'"
		exit
	fi

	base_name="$1"

	if [ ! -f /opt/${base_name}/custom/php-cli.sh ] ; then
		echo "File: '/opt/${base_name}/custom/php-cli.sh' not exists. Installing..."
		sh /script/phpm-installer ${base_name}
	else
		echo "${base_name}" > ${INIT_DIR}/kloxo_php_active
	fi
else
	if [ -f ${INIT_DIR}/php_active ] ; then
		'mv' -f ${INIT_DIR}/php_active ${INIT_DIR}/kloxo_php_active
	fi

	if [ -f ${INIT_DIR}/kloxo_php_active ] ; then
		base_name="$(cat ${INIT_DIR}/kloxo_php_active)"
	else
		base_name="php54s"

		if [ ! -f /opt/${base_name}/custom/php-cli.sh ] ; then
			echo "File: '/opt/${base_name}/custom/php-cli.sh' not exists. Installing..."
			sh /script/phpm-installer ${base_name}
		fi

		echo "${base_name}" > ${INIT_DIR}/kloxo_php_active
	fi
fi

mkdir -p /opt/${base_name}/custom

if [ -f /opt/${base_name}/custom/custom.php.ini ] ; then
	'cp' -f /opt/${base_name}/custom/custom.php.ini /opt/${base_name}/custom/php.ini
fi

chown -R root:root /opt/${base_name}

'rm' -f /usr/bin/lphp.exe
'rm' -f /usr/bin/lxphp.exe

ln -sf /opt/${base_name}/custom/php-cli.sh /usr/bin/lphp.exe
ln -sf /opt/${base_name}/custom/php-cli.sh /usr/bin/lxphp.exe

'cp' -f ${INIT_DIR}/kloxo.init /etc/rc.d/init.d/kloxo
chown root:root /etc/rc.d/init.d/kloxo
chmod 0775 /etc/rc.d/init.d/kloxo

echo "Execute fixlxphpexe for ${base_name}..."
